const express = require('express');
const db = require('./database');
const path = require('path');
const app = express();
const port = 3000;

// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));

// 允许解析 JSON 请求体
app.use(express.json());

// 获取所有任务
app.get('/tasks', (req, res) => {
    db.all('SELECT * FROM tasks', (err, rows) => {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        res.json(rows);
    });
});

// 添加任务
app.post('/tasks', (req, res) => {
    const { name, dueDate, tag, quadrant } = req.body;
    db.run(
        'INSERT INTO tasks (name, dueDate, tag, quadrant) VALUES (?, ?, ?, ?)',
        [name, dueDate, tag, quadrant],
        function (err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json({ id: this.lastID });
        }
    );
});

// 更新任务
app.put('/tasks/:id', (req, res) => {
    const { id } = req.params;
    const { name, dueDate, tag, quadrant } = req.body;
    db.run(
        'UPDATE tasks SET name = ?, dueDate = ?, tag = ?, quadrant = ? WHERE id = ?',
        [name, dueDate, tag, quadrant, id],
        function (err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json({ changes: this.changes });
        }
    );
});

// 更新任务象限
app.put('/tasks/:id/quadrant', (req, res) => {
    const { id } = req.params;
    const { quadrant } = req.body;
    db.run(
        'UPDATE tasks SET quadrant = ? WHERE id = ?',
        [quadrant, id],
        function (err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json({ changes: this.changes });
        }
    );
});

// 标记任务为完成
app.put('/tasks/:id/complete', (req, res) => {
    const { id } = req.params;
    db.run(
        'UPDATE tasks SET completed = 1 WHERE id = ?',
        [id],
        function (err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json({ changes: this.changes });
        }
    );
});

// 删除任务
app.delete('/tasks/:id', (req, res) => {
    const { id } = req.params;
    db.run('DELETE FROM tasks WHERE id = ?', [id], function (err) {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        res.json({ changes: this.changes });
    });
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});